<?php

namespace qmq\tp6\controller;

use app\home\model\QUser;
use think\facade\Console;
use think\facade\Db;

use think\helper\Arr;



class Gii
{

    public function index()
    {

        // $model = new QUser();
        // $user = $model->with(['token'])->find(1);
        // p($user);


        $tables = [];

        $db = Arr::get(Db::getConfig("connections"), Db::getConfig("default") . ".database");
        $tablesSource = Db::query('SELECT * from information_schema.tables WHERE table_schema=:db ', ['db' => $db]);

        foreach ($tablesSource as $table) {
            $table = array_change_key_case($table);
            $fiels = Db::getFields($table['table_name']);
            $table['fields'] = array_values($fiels);
            $tables[] = $table;
        }

        return view(GII_VIEW_PATH, ["tables" => json_encode($tables)]);
    }

    public function model()
    {
        $main = input("post.main");

        //return json(input());
        // [
        //     "q_user",
        //     '--namespace=app\home\model',
        //     //"--name=Test"
        //     //"--extend=BaseModel"
        //     '--relations=[{"table":"q_user_token","relation_name":"token","type":"hasOne","foreign":"uid","mainkey":"id"}]'
        // ];

        if (!Arr::get($main, 'table')) {
            return json(['code' => 0, "msg" => '主表必须存在']);
        }

        $args = [
            $main['table'], //主表名
        ];

        //主表模型的名称
        $name = Arr::get($main, 'name');
        if ($name) {
            array_push($args, "--name=" . $name);
        }

        //主表所在的命名空间
        $namespace = Arr::get($main, 'namespace');
        if ($namespace) {
            array_push($args, "--namespace=" . $namespace);
        }

        //继承
        $extend = Arr::get($main, 'extend');
        if ($extend) {
            array_push($args, "--extend=" . $extend);
        }

        //软删除
        $soft = Arr::get($main, 'soft');
        array_push($args, "--soft=" . ($soft ? 1 : 0));


        //关联表
        $relations = input("post.relations");
        if ($relations) {
            array_push($args, "--relations=" . json_encode($relations));
        }
        Console::call("qmq:model", $args);
        return json(["code" => 200, "msg" => "生成成功"]);
    }
}
